﻿using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp.TestFunc.测试代码
{

    public static class DITest6
    {
        public interface IAccount { }
        public interface IMessage { }
        public interface ITool { }

        public class Base : IDisposable
        {
            public Base()
            {
                Console.WriteLine($"创建：{GetType().Name}");
            }
            public void Dispose()
            {
                Console.WriteLine($"释放：{GetType().Name}");
            }
        }


        public class Account : Base, IAccount { }
        public class Message : Base, IMessage { }
        public class Tool : Base, ITool { }
        public static void Run()
        {
            using (var root = new ServiceCollection()
            .AddTransient<IAccount, Account>()
            .AddScoped<IMessage, Message>()
            .AddSingleton<ITool, Tool>()
            .BuildServiceProvider())
            {
                using (var scope = root.CreateScope())
                {
                    var child = scope.ServiceProvider;
                    child.GetService<IAccount>();
                    child.GetService<IMessage>();
                    child.GetService<ITool>();
                    Console.WriteLine("释放 子 容器");
                }
                Console.WriteLine("释放 根 容器");
            }
        }
    }
}
